
$(document).ready(function(){
	loadUserOrgsData();
	loadUsers();
});


var UserOrgZTree,showOrgZTree,addUserOrgZTree,impowerOrgTree,impowerResTree,UserOrgRMenu;
var userOrgTreeSetting = {	
		data:{
			key:{
				name:"name"
			},
			simpleData:{
				enable:true,
				idKey:"orgId",
				pIdKey:"parentOrgId",
				rootPId:0
			}
		},
		callback:{
			onClick:loadUserOrgByOrgId,
			onRightClick:userRightClick
		}
	};
	/**
	 * 加载模块树形数据
	 */
	function loadUserOrgsData(){
		var url = appCtx + "secure/user/loadUserOrgsData.html";
		$.post(url,function(data){ 
			UserOrgZTree=$.fn.zTree.init($("#userOrgTree"), userOrgTreeSetting, data);
		});
		UserOrgRMenu = $("#userOrgRMenu");
	}

	function loadUserOrgByOrgId(event,treeId,treeNode){
		var orgId = treeNode.orgId;
		var name = treeNode.name;
		UserRefreshOrgBody(orgId,name);
	}

	function UserRefreshOrgBody(orgId,name){
		$("#uorgId").val(orgId);
		$("#uname").val(name);
		queryUser();
	}
	
	function userRightClick(event, treeId, treeNode){
		if (!treeNode && event.target.tagName.toLowerCase() != "button" && $(event.target).parents("a").length == 0) {
			UserOrgZTree.cancelSelectedNode();
			showUserOrgRMenu("root", event.clientX, event.clientY);
		} else if (treeNode && !treeNode.noR) {
			UserOrgZTree.selectNode(treeNode);
			showUserOrgRMenu("node", event.clientX, event.clientY);
		}
		
	}

	function showUserOrgRMenu(type, x, y) {
		y=y-78;
		$("#userOrgRMenu ul").show();
		$("#addUser").show();
		UserOrgRMenu.css({"top":y+"px", "left":x+"px", "visibility":"visible"});
		$(".userView").bind("mousedown", onUserOrgBodyMouseDown);
	}

	function hideUserOrgRMenu() {
		if (UserOrgRMenu) UserOrgRMenu.css({"visibility": "hidden"});
		$(".userView").unbind("mousedown", onUserOrgBodyMouseDown);
	}
	function onUserOrgBodyMouseDown(event){
		if (!(event.target.id == "UserOrgRMenu" || $(event.target).parents("#userOrgRMenu").length>0)) {
			UserOrgRMenu.css({"visibility" : "hidden"});
		}
	}

	function userCheckTreeNode(checked,treeId, treeNode) {
		var nodes = orgZTree.getSelectedNodes();
		if (nodes && nodes.length>0) {
			orgZTree.checkNode(nodes[0], checked, true);
		}
		hideUserOrgRMenu();
	}
	
	/**
	 * 点击选择按钮加载组织树
	 */
	var querySetting = {
		view: {
			dblClickExpand: false
		},
		data:{
			key:{
				name:"name"
			},
			simpleData:{
				enable:true,
				idKey:"orgId",
				pIdKey:"parentOrgId",
				rootPId:0
			}
		},
		callback: {
			onClick:loadUserOrgByOrgId,
			onClick: userOnClick
		}
	};
	
	function userOnClick(e, treeId, treeNode) {
		var orgName = treeNode.name;
		var orgId = treeNode.orgId;
		var orgObj = $("#uname");
		orgObj.attr("value", orgName);
		$("#uorgId").val(orgId);
		userHideMenu();
	}

	function showOrgTree() {
		var url = appCtx + "secure/user/loadUserOrgsData.html";
		$.post(url,function(data){ 
			showOrgZTree = $.fn.zTree.init($("#showOrgTree"), querySetting, data);
		});
		
		var orgObj = $("#uname");
		var userOrgOffset = $("#uname").offset();
		$("#umenuContent").css({left:userOrgOffset.left + "px", top:(userOrgOffset.top + orgObj.outerHeight()-76) + "px"}).show();
		$("body").bind("mousedown", userOnBodyDown);
		
	}
	
	function userHideMenu() {
		$("#umenuContent").fadeOut("fast");
		$(".userView").unbind("mousedown", userOnBodyDown);	
	}
	
	function userOnBodyDown(event) {
		if (!(event.target.id == "menuBtn" || event.target.id == "umenuContent" || $(event.target).parents("#umenuContent").length>0)) {
			userHideMenu();
		}
	}
	
	
	/**
	 * 新增用户时点击选择按钮加载组织树
	 */
	var addsetting = {
		view: {
			dblClickExpand: false
		},
		data:{
			key:{
				name:"name"
			},
			simpleData:{
				enable:true,
				idKey:"orgId",
				pIdKey:"parentOrgId",
				rootPId:0
			}
		},
		callback: {
			onClick:loadUserOrgByOrgId,
			onClick: onClickOrg
		}
	};
	
	function onClickOrg(e, treeId, treeNode) {
		var orgName = treeNode.name;
		var orgId = treeNode.orgId;
		var orgObj = $("#orgName");
		orgObj.attr("value", orgName);
		$("#userOrgId").val(orgId);
		hideMenus();
	}

	function addUserOrgTree() {
		var url = appCtx + "secure/user/loadUserOrgsData.html";
		$.post(url,function(data){ 
			addUserOrgZTree = $.fn.zTree.init($("#addUserOrgTree"), addsetting, data);
		});
		
		var orgObj = $("#orgName");
		var userOrgOffset = $("#orgName").offset();
		$("#addmenuContent").css({left:(userOrgOffset.left - 290)+ "px", top:(userOrgOffset.top + orgObj.outerHeight()-233) + "px"}).slideDown("fast");
		$("body").bind("mousedown", onBodyDown);
		
	}
	
	function hideMenus() {
		$("#addmenuContent").fadeOut("fast");
		$(".model").unbind("mousedown", onBodyDown);	
	}
	
	function onBodyDown(event) {
		if (!(event.target.id == "menuBtn" || event.target.id == "addmenuContent" || $(event.target).parents("#addmenuContent").length>0)) {
			hideMenus();
		}
	}
	
	/**
	 * 授权组织树
	 */
	var impowerOrgsetting = {
		view: {
			dblClickExpand: false
		},
		check: {
			enable: true
		},
		data:{
			key:{
				name:"name"
			},
			simpleData:{
				enable:true,
				idKey:"orgId",
				pIdKey:"parentOrgId",
				rootPId:0
			}
		},
		callback: {
			onCheck:getCheckedNodes
		}
	};
	
	function getCheckedNodes(){
		var treeObj = $.fn.zTree.getZTreeObj("impowerOrgTree");
		var nodes = treeObj.getCheckedNodes(true);
		var orgIdArray = new Array();
		for(var i=0;i<nodes.length;i++){
			var node = nodes[i];
			var halfCheck = node.getCheckStatus().half;
			if(halfCheck == false){
				orgIdArray.push(node.orgId);
			}
		}
		$("#orgIds").val(orgIdArray.join(","));
	}
	
	/**
	 * 授权资源树
	 */
	var impowerRessetting = {
		view: {
			dblClickExpand: false
		},
		check: {
			enable: true
		},
		data:{
			key:{
				name:"treeName"
			},
			simpleData:{
				enable:true,
				idKey:"treeId",
				pIdKey:"parentId",
				rootPId:0
			}
		},
		callback: {
			onCheck:getResCheckedNodes
		}
	};
	
	function getResCheckedNodes(){
		var treeObj = $.fn.zTree.getZTreeObj("impowerResTree");
		var nodes = treeObj.getCheckedNodes(true);
		
		var resIdArray = new Array();
		for(var i=0;i<nodes.length;i++){
			var node = nodes[i];
			var halfCheck = node.getCheckStatus().half;
			if(halfCheck == false){
				resIdArray.push(node.treeId);
			}
		}
		$("#resTreeIds").val(resIdArray.join(","));
	}
	/**
	 * 用户信息列表
	 */
	function loadUsers(){
		$("#userContainer").jtable({
			title:"",
			paging:true,
			pageSize:10,
			gotoPageArea:'none',
			columnSelectable: false,
			pageSizeChangeArea:false,
			selectingCheckboxes:true,
			selecting: true, //Enable selecting
            multiselect: true, //Allow multiple selecting
            //selectOnRowClick: false, //Enable this to only select using checkboxes
			actions:{
				listAction:appCtx + "secure/user/loadAllUsers.html"
			},
			fields:{
				userId:{
					key:true,
					list:false
				},
				
				userName:{
					title:"用户名称",
					width:"10%"
				},
				loginName:{
					title:"登陆账号",
					width:"10%"
				},
				mobilePhone:{
					title:"手机号码",
					width:"10%"
				},
				officePhone:{
					title:"办公电话",
					width:"10%"
				},
				email:{
					title:"电子邮箱",
					width:"15%"
				},
				orgName:{
					title:"所属部门",
					width:"10%"
				},
				remark:{
					title:"备注",
					width:"10%"
				},
				operation:{
					title:"修改",
					width:"5%",
					userData:true,
					content:$("#updateUser").html(),
					param:"userId"
				}
			}
		});
		
		queryUser();
	}

	function queryUser(){
		var params = $("#queryUserForm").serialize();
		$("#userContainer").jtable("load",params);
	}
	
	
	/**
	 * 修改当前用户密码
	 * @param moduleId
	 */
	function savePw(){
		var validate = $("#pwUpdateForm").validationAjax();
		if(validate){
			var userName = $("#userName").val();
			var userId = $("#userId").val();
			msg = "确认修改用户［"+userName+"］的密码吗?";
			if(confirm(msg)==true){
				var url =appCtx +  "secure/user/updatePw.html";
				var params = $("#pwUpdateForm").serialize();
				$.post(url,params,function(result){
					var flag = result.flag;
					if(flag=="fail"){
						$("#checkInfo").html("与原密码不一致,请重新输入!");
						$("#pwUpdateForm")[0].reset() ;
						$("#selfPassword").focus(function(){
							$("#checkInfo").html("");
						});

					}
					else if(flag=="ok"){
						$(".alert").css("visibility","visible").addClass("alert-success").html("修改成功，新密码下次登陆生效!");
						window.setTimeout(function(){
							$(".alert").css("visibility","hidden").removeClass("alert-success")
						}, 2000);
						$("#pwUpdateForm")[0].reset() ;
//						pwUpdateForm.reset() ;
					}
					else if(flag=="error"){
						$(".alert").css("visibility","visible").addClass("alert-error").html("修改失败!");
						window.setTimeout(function(){
							$(".alert").css("visibility","hidden").removeClass("alert-error")
						}, 2000);
					}
				});
				validate = false;
			}
			else{
				validate = false;
			}
		}
		return validate;
	}
	
		
	/**
	 * 新增用户
	 * */
	function addUser(){
		hideUserOrgRMenu();
		
		var url = appCtx + "secure/user/initUser.html";
		$.post(url,function(data){
			$("#addUserModal .modal-body").html(data);
			$("#userTitle").html("新增用户");
			
			var userOrgTree = $.fn.zTree.getZTreeObj("userOrgTree");
			var nodes = userOrgTree.getSelectedNodes();
			var node = nodes[0];
			$("#userOrgId").val(node.orgId);
			$("#orgName").val(node.name);
			
			//加载组织树
			var urlOrg = appCtx + "secure/user/loadUserOrgsData.html";
			$.post(urlOrg,function(data){ 
				impowerOrgTree = $.fn.zTree.init($("#impowerOrgTree"), impowerOrgsetting, data);
			});
			//加载资源树
			var urlRes = appCtx + "secure/resconfig/qryAllResTree.html";
			$.post(urlRes,function(data){ 
				impowerResTree=$.fn.zTree.init($("#impowerResTree"), impowerRessetting, data);
			});
			
			$("#addUserModal").modal();
		});
		
	}
	
	function addUserButton(){
		hideUserOrgRMenu();
		
		var url = appCtx + "secure/user/initUser.html";
		$.post(url,function(data){
			$("#addUserModal .modal-body").html(data);
			$("#userTitle").html("新增用户");
		});
		//加载组织树
		var urlOrg = appCtx + "secure/user/loadUserOrgsData.html";
		$.post(urlOrg,function(data){ 
			impowerOrgTree = $.fn.zTree.init($("#impowerOrgTree"), impowerOrgsetting, data);
		});
		//加载资源树
		var urlRes = appCtx + "secure/resconfig/qryAllResTree.html";
		$.post(urlRes,function(data){ 
			impowerResTree=$.fn.zTree.init($("#impowerResTree"), impowerRessetting, data);
		});	
		$("#addUserModal").modal();
	}
	/**
	 * 保存用户
	 * */
	 function saveUser(){ 
		 var flag = $("#addUserForm").validationAjax();
			if(flag){
				var orgIds = $("#orgIds").val();		
				var resTreeIds = $("#resTreeIds").val();
				var url = appCtx + "secure/user/saveUser.html";
				var params = $("#addUserForm").serialize()+"&orgIds="+orgIds+"&resTreeIds="+resTreeIds;
				$.post(url,params,function(data){
					$("#userContainer").jtable("reload");
					$("#addUserModal").modal("hide");
				});
			}
			return flag;
	 }
	 
	 
	 /**
	  * 修改用户
	  * */
	 function updateUser(userId){
		var url = appCtx + "secure/user/updateUser.html";
		$.post(url,{userId:userId},function(data){
			$("#addUserModal .modal-body").html(data);
			$("#userTitle").html("修改用户");
			$("#passwords").hide();
			$("#password").val("1");
			$("#confirm").val("1");
			
			//加载组织树
			var urlOrg = appCtx + "secure/user/loadUserOrgsData.html";
			$.post(urlOrg,function(data){ 
				impowerOrgTree = $.fn.zTree.init($("#impowerOrgTree"), impowerOrgsetting, data);
				parseOrgIds(impowerOrgTree);
			});
			//加载资源树
			var urlRes = appCtx + "secure/resconfig/qryAllResTree.html";
			$.post(urlRes,function(data){ 
				impowerResTree=$.fn.zTree.init($("#impowerResTree"), impowerRessetting, data);
				parseResTreeIds(impowerResTree);
			});
		});
		$("#addUserModal").modal();
		
	}
	 /**
	  * 批量删除
	  * */
	function delUsers(){
        var $selectedRows = $('#userContainer').jtable('selectedRows');
        var userIdArray = new Array();
        $selectedRows.each(function () {
    	    var record = $(this).data('record');
    	    var userId = record.userId;
    	    userIdArray.push(userId);  
    	});
 		var url = appCtx + "secure/user/delUser.html";
 		if(userIdArray.length == 0){
			alert("请勾选需要删除的数据！");
			return;
		}
		if(confirm("确定要删除吗？删除后将无法恢复！")){
			$.post(url,{userIds:userIdArray.join(",")},function(data){
	 			$('#userContainer').jtable('reload');
	 		});
		}        
	 }
	/**
	 * 批量重置默认密码
	 * */
	function resetPassword(){
		var $selectedRows = $('#userContainer').jtable('selectedRows');
        var userIdArray = new Array();
        $selectedRows.each(function () {
    	    var record = $(this).data('record');
    	    var userId = record.userId;
    	    userIdArray.push(userId);  
    	});
 		var url = appCtx + "secure/user/resetPassword.html";
 		if(userIdArray.length == 0){
			alert("请勾选需要重置密码的数据！");
			return;
		}
		if(confirm("确定要重置密码吗？重置密码后原密码将失效！")){
			$.post(url,{userIds:userIdArray.join(",")},function(data){
	 			$('#userContainer').jtable('reload');
	 		});
		}        
	}
	
	function resets(){	
		$("#uname").attr("value","");
		$("#uorgId").attr("value","");
		return;
	}
	/**
	 * 密码校验
	 * 
	 */
	function checkConfirm(value){
		var flag = false;
		var password = $("#password").val();
		var confirm = $("#confirm").val();
		if((password!=null && password!="")&& confirm==""){ // 如果是更新,则不检查权限编码;如果是保存,则检查
			flag = true;				
		}
		return flag;
	}
	function checkPassword(value){
		var flag = false;
		var password = $("#password").val();
		var confirm = $("#confirm").val();
		var userPassword = $("#newPassword").val();
		var userConfirm = $("#checkPassword").val();
		if((password!=confirm)||(userPassword!=userConfirm)){ // 如果是更新,则不检查权限编码;如果是保存,则检查
			flag = true;				
		}
		return flag;
	}
	
	function parseOrgIds(impowerOrgTree){
		var orgIds = $("#orgIds").val();
		if(orgIds!=""){
			impowerOrgTree.expandAll(true);
			var array = orgIds.split(",");
			for(var i=0;i<array.length;i++){
				var currentNode = impowerOrgTree.getNodeByParam("orgId",array[i],null);
				impowerOrgTree.checkNode(currentNode,true,true);
			}
		}
	}
	
	function parseResTreeIds(impowerResTree){
		var resTreeIds = $("#resTreeIds").val();
		if(resTreeIds!=""){
			impowerResTree.expandAll(true);
			var array = resTreeIds.split(",");
			for(var i=0;i<array.length;i++){
				var currentNode = impowerResTree.getNodeByParam("treeId",array[i],null);
				impowerResTree.checkNode(currentNode,true,true);
			}
		}
	}